package org.heart.springsecurity.result;

import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author PC
 */
public class ApiResponse {


    public static String isSuccess(Object o) {
        if (o instanceof Integer) {
            return (int) o == 1 ? success() : fail();
        }
        return fail();
    }

    public static String ListIsEmpty(Collection<?> list) {
        return list.isEmpty() ? success(new ArrayList<>()) : success(list);
    }


    public static String success(Object anObject) {
        return json(200, "success", anObject);
    }

    public static String success() {
        return json(200, "success", null);
    }

    public static String success(String message, Object anObject) {
        return json(200, message, anObject);
    }

    public static String success(int code, String message, Object anObject) {
        return json(code, message, anObject);
    }

    public static String success(String message) {
        return json(200, message, null);
    }

    public static String fail(Object anObject) {
        return json(400, "fail", anObject);
    }

    public static String fail(String message, Object anObject) {
        return json(400, message, anObject);
    }

    public static String fail(int code, String message, Object anObject) {
        return json(code, message, anObject);
    }

    public static String fail(String message) {
        return json(400, message, null);
    }

    public static String fail(int code, String message) {
        return json(code, message, null);
    }

    public static String fail() {
        return json(400, "fail", null);
    }

    protected static String json(int code, String message, Object data) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", message);
        jsonObject.put("data", data);
        return jsonObject.toJSONString();
    }
}

